package com.example.backend.service.impl;

import com.example.backend.Requset.CreateRoomRequest;
import com.example.backend.dao.LogsRepository;
import com.example.backend.dao.RoomRepository;
import com.example.backend.dao.UserRepository;
import com.example.backend.pojo.Logs;
import com.example.backend.pojo.Room;
import com.example.backend.pojo.User;
import com.example.backend.service.RoomService;
import com.example.backend.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LogsRepository logsRepository;

    @Override
    public Response<List<Room>> findAll(){
        List<Room> rooms=roomRepository.findAll();
        return new Response<>(Response.SUCCESS,"success",rooms);
    }

    @Override
    public Response<Room> createRoom(CreateRoomRequest room){
        User creator=userRepository.findUserByUsername(room.getCreator());
        if (creator==null){
            return new Response<>(Response.FAIL,"no such creator",null);

        }
        Room newRoom=new Room(0,room.getName(),creator.getId(),room.getTime(),1);
        Room sameNameRoom=roomRepository.findRoomByName(room.getName());
        if (sameNameRoom==null){
            Logs userLog=logsRepository.findLogsByUserID(creator.getId());
            if (userLog!=null){
                return new Response<>(Response.FAIL,"already in room",null);
            }
            roomRepository.save(newRoom);
            Room createRoom=roomRepository.findRoomByName(room.getName());
            Logs log = new Logs(0, creator.getId(), createRoom.getId(), room.getTime(), "0", true);
            logsRepository.save(log);
            return new Response<>(Response.SUCCESS,"success",null);
        }else {
            Room createRoom=roomRepository.findRoomByName(room.getName());
            if(createRoom.getNum() > 0){
                return new Response<>(Response.FAIL, "exist room", null);
            }
            return new Response<>(Response.SUCCESS,"success",null);
        }
    }
}
